<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #container{
            height: 500px;
            position: relative;
            overflow: auto;
            border: 1px solid black;
        }
        #occupied{
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            z-index: -1;
        }
        /* 虚拟列表定位 */
        #list{
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            background-color: red;
        }
    </style>
</head>

<body>
    <section id="container">
        <div id="occupied"></div> <!-- 占位 -->
        <div id="list"></div> <!-- 列表容器 -->
    </section>
    <script>
        // arr 为数据列表，这里表示有十万条数据
        const arr = []
        for (let index = 0; index < 100000; index++) {
            arr.push(index)
        }
        // 获取相关dom结构
        const container = document.getElementById("container")
        const occupied = document.getElementById("occupied")
        const list = document.getElementById("list")
        // 定义相关使用变量
        let screenHeight = container.clientHeight
        let startOffset = 0, startIndex = 0, itemSize = 20

        // 定义相关方法
        const getEndIndex = () => startIndex + Math.ceil(screenHeight / itemSize)

        const getVirtualRenderArr = () => {
            _end = Math.min(getEndIndex(), arr.length)
            return arr.slice(startIndex, _end)
        }

        const init = () => {
            // 初始化
            occupied.style.height = `${arr.length * itemSize}px`
        }

        init()
        // 添加相关结构，渲染虚拟列表
        getVirtualRenderArr().forEach(_i => {
            const node = document.createElement("div")
            const textNode = document.createTextNode(_i)
            node.appendChild(textNode)
            document.getElementById("list").appendChild(node)
        })
        /*
        滚动时的处理
        1. 首先绑定滚动事件
        2. 滚动时处理虚拟列表
        */ 
    </script>
</body>

</html>